<template>
  <div class="approver">
    <div class="approver-item" v-for="(item, index) in approver" :key="index">
      <div class="approver-item-c">
        <el-avatar :src="headerImgSrc"></el-avatar>
        <el-tag
          type="success"
          @close="handleDelOpportunitiesApprover(index)"
          :closable="!readonly"
          size="medium"
          >
          {{item.type===1? item.showName || item.approvalName || item.userName :item.roleName||item.userName}}
        </el-tag>
        <div v-if="!isCc">第{{index+1}}级{{item[0].type===1?'审批人':'角色'}}</div>
        <!-- <template v-if="!isCc && typeof(item.state) === 'number' && item.state !== 0 && !isEdit">
          <div>{{ item.byTheDate }}</div>
          <div>{{ item.state | stateNameFilter }}</div>
          <div>审批意见：{{ item.approvalOpinion }}</div>
        </template> -->
      </div>
      <div v-if="!isCc && index !== approver.length - 1">
        <i class="el-icon-right"></i>
      </div>
    </div>
    <div v-if="!readonly">
      <!-- <el-button
        size="medium"
        type="text"
        round
        @click="approverDialog = true;handleAddPeople()"
        style="position: relative; top: -3px; left: -10px"
      >
        {{ isCc ? "添加抄送人" : "添加审批人" }}
      </el-button> -->
      <el-button
        v-if="role"
        size="medium"
        type="text"
        round
        @click="roleDialog = true;"
        style="position: relative; top: -3px; left: -10px"
      >添加角色</el-button>
    </div>
    <el-dialog
      :title="addTitle"
      :visible.sync="approverDialog"
      append-to-body
      width="700px"
      class="group-dialog"
    >
      <div class="approver-inquiry">
        <el-form
          :model="groupParams"
          label-width="75px"
          size="mini"
          ref="ruleForm"
          label-position="right"
          @submit.native.prevent
          class="login-name"
        >
          <el-form-item label="员工姓名" prop="showName">
            <el-input
              class="filter-item"
              v-model="groupParams.showName"
              :clearable="true"
              placeholder="员工姓名"
            />
          </el-form-item>
        </el-form>
        <el-button
          class="aaa"
          slot="operator"
          type="primary"
          :plain="true"
          size="mini"
          @click="getUserList(true)"
          >查询</el-button
        >
      </div>
      <div>
        <el-table
          ref="multipleTable"
          :data="groupList"
          size="mini"
          header-cell-class-name="table-header-gray"
          style="width: 100%"
          :row-key="getRowKeyPersonnel"
          @selection-change="handleSelectionChange(1)"
        >
          <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
          <el-table-column label="用户名" prop="loginName"> </el-table-column>
          <el-table-column label="员工姓名" prop="showName"> </el-table-column>
          <el-table-column label="部门" prop="deptIdDictMap.name"> </el-table-column>
          <el-table-column label="账号类型" prop="userTypeDictMap.name" />
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-tag
                :type="getUserStatusType(scope.row.userStatus)"
                size="mini"
                >{{ SysUserStatus.getValue(scope.row.userStatus) }}</el-tag
              >
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" align="center" fixed="right" width="80">
            <template slot-scope="{ row }">
              <el-button
                type="primary"
                @click="
                  approverDialog = false;
                  handleChooseapprover(row);
                "
                size="mini"
                >选择</el-button
              >
            </template>
          </el-table-column> -->
        </el-table>
        <el-row type="flex" justify="end" style="margin-top: 10px">
          <el-pagination
            background
            @size-change="handleSizeChangeGroup"
            @current-change="handleCurrentChangeGroup"
            :current-page="groupParams.pageNo"
            :page-size="groupParams.page_size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            :total="groupTotal"
          ></el-pagination>
        </el-row>
        
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="approverDialog = false; handleClose()" size="small">取 消</el-button>
        <el-button type="primary" @click="approverDialog = false; handleChooseapprover(1)" size="small">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 角色 -->
    <el-dialog
      title="添加角色"
      :visible.sync="roleDialog"
      append-to-body
      width="700px"
      class="group-dialog"
    >
      <!-- <div class="approver-inquiry">
        <el-form
          :model="roleParams"
          label-width="75px"
          size="mini"
          ref="ruleForm"
          label-position="right"
          @submit.native.prevent
          class="login-name"
        >
          <el-form-item label="角色" prop="showName">
            <el-input
              class="filter-item"
              v-model="roleParams.roleName"
              :clearable="true"
              placeholder="请输入角色"
            />
          </el-form-item>
        </el-form>
        <el-button
          class="aaa"
          slot="operator"
          type="primary"
          :plain="true"
          size="mini"
          @click="getRoleList(true)"
          >查询</el-button
        >
      </div> -->
      <div>
        <el-table
          ref="multipleRoleTable"
          :data="roleList"
          size="mini"
          header-cell-class-name="table-header-gray"
          style="width: 100%"
          :row-key="getRowKeyRole"
          @selection-change="handleSelectionChange(2)"
        >
          <!-- <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column> -->
          <el-table-column label="角色" prop="roleName"> </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="80">
            <template slot-scope="{ row }">
              <el-button
                type="primary"
                @click="
                  roleDialog = false;
                  handleChooseapprover(row, 2);
                "
                size="mini"
                >选择</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="margin-top: 10px">
          <el-pagination
            background
            @size-change="handleSizeChangeGroupR"
            @current-change="handleCurrentChangeGroupR"
            :current-page="roleParams.pageNo"
            :page-size="roleParams.page_size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            :total="groupTotal"
          ></el-pagination>
        </el-row>
        
      </div>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button @click="roleDialog = false; handleRoleClose()" size="small">取 消</el-button> -->
        <!-- <el-button type="primary" @click="roleDialog = false; handleChooseapprover(2)" size="small">确 定</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>
<script>
import headerImgSrc from '@/assets/img/default-header.png'
import { SystemController } from '@/api';
import { Contracts } from '@/api/projectAdministration.js';
// import { BusinessOpportunities } from '@/api/commercial.js';
const stateNameArr = [
  '待审核',
  '审核通过',
  '审核驳回'
];
// BusinessOpportunities.selectDivision
export default {
  filters: {
    approverFilter (val) {
      const data = {
        0: '一',
        1: '二',
        2: '三',
        3: '四',
        4: '五',
        5: '六',
        6: '七',
        7: '八',
        8: '九',
        9: '十',
        10: '十一',
        11: '十二',
        12: '十三',
        13: '十四',
        14: '十五',
        15: '十六',
        16: '十七',
        17: '十八',
        18: '十九',
        19: '二十',
        20: '二十一',
        21: '二十二',
        22: '二十三',
        23: '二十四',
        24: '二十五',
        25: '二十六',
        26: '二十七',
        27: '二十八',
        28: '二十九',
        29: '三十'
      };
      return data[val];
    },
    stateNameFilter (state) {
      return stateNameArr[state];
    }
  },
  props: {
    // 请求用户列表的函数
    getUserFn: {
      type: Function,
      default: SystemController.getUserList
    },
    // 请求用户列表的函数
    getRoleFn: {
      type: Function,
      default: SystemController.getRoleList
    },
    // 审批人类型，1-商机任务;3-项目立项;4-项目任务;21-盖章申请;22-用车审批;23-投标审批;24-合同盖章审批;25-资质盖章审批;50-合同盖章;52-合同会审
    typeId: {
      default: undefined
    },
    // 是否为抄送
    isCc: {
      type: Boolean,
      default: false
    },
    // 角色按钮是否显示
    role: {
      type: Boolean,
      default: false
    },
    // 回显的话为true
    readonly: {
      type: Boolean,
      default: false
    },
    // 是否为编辑
    isEdit: {
      type: Boolean,
      default: false
    },
    approverList: {
      default: undefined
    }
  },
  data () {
    return {
      addTitle: '添加审批人',
      headerImgSrc: headerImgSrc,
      approverDialog: false,
      roleDialog: false,
      approver: [],
      groupList: [],
      roleList: [],
      isApprover: '',
      List: [],
      listrole: [],
      showName: '',
      approvalLevel: '',

      groupTotal: 0,
      roleTotal: 0,
      groupParams: {
        // loginName: '',
        showName: '',
        page_size: 10,
        pageNo: 1
      },
      roleParams: {
        roleName: '',
        page_size: 10,
        pageNo: 1
      },
      // 当前用户的已选审批人列表
      hasChosenApprovaerList: []
    }
  },
  created () {
    if (this.approverList && this.approverList.length > 0) {
      this.approver = this.approverList;
    }
    this.getUserList(true);
    if (this.typeId) {
      this.queryTaskApprovaer(this.typeId);
    }
    this.getRoleList(true);
    // if (this.typeId) {
    //   this.queryTaskApprovaer(this.typeId);
    // }
  },
  watch: {
    approverList () {
      if (this.approverList) {
        this.approver = this.approverList;
      }
    },
    typeId (newVal, oldVal) {
      this.queryTaskApprovaer(this.typeId);
    }
  },
  methods: {
    // 获取人员表格列表唯一值 id
    getRowKeyPersonnel (row) {
      return row.userId;
    },
    // 获取角色表格列表唯一值 id
    getRowKeyRole (row) {
      return row.roleId
    },
    // 获取复选框多选数据
    handleSelectionChange (type) {
      this.isApprover = type
      if (type === 1) {
        this.List = this.$refs.multipleTable.selection.map(item => {
          return {
            ...item,
            type: type
          }
        })
      } else {
        this.List = this.$refs.multipleRoleTable.selection.map(item => {
          return {
            ...item,
            type: type,
            userId: item.roleId,
            userName: item.roleName
          }
        })
      }
      console.log('%^%^%^', this.List)
    },
    // 关闭审批人选择弹窗，清空多选
    handleClose () {
      this.$refs.multipleTable.clearSelection();
    },
    // 关闭审批角色选择弹窗，清空多选
    handleRoleClose () {
      this.$refs.multipleRoleTable.clearSelection();
    },
    handleAddPeople () {
      if (this.isCc) {
        this.addTitle = '添加抄送人'
      } else {
        this.addTitle = '添加审批人'
      }
    },
    // 获取当前登录用户的已选审批人列表
    queryTaskApprovaer (typeId) {
      if (this.readonly || this.isCc) {
        return false;
      }
      let params = {
        id: typeId
      };
      return new Promise((resolve, reject) => {
        Contracts.queryTaskApprovaer(this, params)
          .then(res => {
            let data = res.data;
            this.approver = data.map((v, i) => {
              v.approvalLevel = i + 1;
              v.showName = v.approvalName;
              return v;
            });
          
            this.$emit('handleChooseapprover', this.approver);
            // resolve(data);
          })
          .catch(e => {
            reject(e);
          });
      });
    },
    // 分页
    handleSizeChangeGroup (val) {
      this.groupParams.page_size = val;
      this.getUserList();
    },
    handleCurrentChangeGroup (val) {
      this.groupParams.pageNo = val;
      this.getUserList();
    },
    // 角色分页
    handleSizeChangeGroupR (val) {
      this.roleParams.page_size = val;
      this.getRoleList();
    },
    handleCurrentChangeGroupR (val) {
      this.roleParams.pageNo = val;
      this.getRoleList();
    },
    // 审批人选择
    handleChooseapprover (row) {
      console.log(row, 234)
      // row.approvalLevel = this.approver?.length + 1;
      this.approver.push(row);
      // this.resetForm();
      this.$emit('handleChooseapprover', this.approver);
    },
    // handleChooseapprover (type) {
    //   this.approver.push(this.List);
    //   console.log(this.approver, '@@@')
    //   if (type === 1) {
    //     this.$refs.multipleTable.clearSelection();
    //   } else if (type === 2) {
    //     this.$refs.multipleRoleTable.clearSelection();
    //   }
    //   if (this.isApprover === 1) {
    //     this.resetForm();
    //   }
    //   this.$emit('handleChooseapprover', this.approver);
    // },

    getUserStatusType (status) {
      if (status === this.SysUserStatus.NORMAL) {
        return 'success';
      } else if (status === this.SysUserStatus.LOCKED) {
        return 'danger';
      } else {
        return 'info';
      }
    },
    // 审批人删除
    handleDelOpportunitiesApprover (index) {
      this.approver.splice(index, 1)
      this.approver.forEach((item, i) => {
        item.approvalLevel = i + 1
      })
      this.$emit('handleChooseapprover', this.approver)
    },
    getUserList (type) {
      if (type) {
        this.groupParams.pageNo = 1;
      }
      return new Promise((resolve, reject) => {
        this.getUserFn(this, {
          orderParam: [{ asc: false, fieldName: 'showName' }],
          pageParam: {
            pageNum: this.groupParams.pageNo,
            pageSize: this.groupParams.page_size
          },
          sysUserDtoFilter: { showName: this.groupParams?.showName }
        }).then((res) => {
          this.groupList = res.data.dataList;
          this.groupTotal = res.data.totalCount;
          resolve(res.data.dataList);
        }).catch((e) => {
          reject(e);
        });
      })
    },
    // 获取角色列表
    getRoleList () {
      // if (type) {
      //   this.roleParams.pageNo = 1;
      // }
      return new Promise((resolve, reject) => {
        this.getRoleFn(this, {
          pageParam: {
            pageNum: this.roleParams.pageNo,
            pageSize: this.roleParams.page_size
          }
        }).then((res) => {
          this.roleList = res.data.dataList;
          this.roleTotal = res.data.totalCount;
          resolve(res.data.dataList);
        }).catch((e) => {
          reject(e);
        });
      })
    },
    // 表单重置
    resetForm () {
      this.$refs['ruleForm'].resetFields();
    },
    // 重置列表
    reset () {
      this.approver = [];
      this.$emit('handleChooseapprover', this.approver);
    }
  }
}
</script>
<style lang="scss" scoped>
.approver {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  .approver-item {
    display: flex;
    justify-content: space-between;
    .approver-item-c {
      padding: 0 10px;
      text-align: center;
      display: flex;
      flex-direction: column;
      align-items: center;
      & > * {
        margin: 5px 0;
      }
    }
  }

  // /deep/.el-tag {
  //   width: 100%;
  //   position: relative;
  // }
  // /deep/.el-tag--medium .el-icon-close {
  //   transform: scale(0.8) translateY(-50%);
  // }
  // /deep/.el-tag .el-icon-close {
  //   position: absolute;
  //   top: 50%;
  //   right: 5px;
  //   transform: translateY(-50%);
  // }
  /deep/.el-form-item__content {
    display: flex;
  }
}
.approver-inquiry {
  display: flex;
  padding: 0 10px;
  line-height: 28px;
  height: 28px;
}
.aaa {
  padding-left: 17px;
  margin-left: 250px;
  position: relative;
  top: -15px;
  left: 5px;
}
.login-name {
  position: relative;
  top: -15px;
  left: -13px;
}
</style>
